package com.sks.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class StringUtil {
	private static final Map<String, String> escapeChars = new HashMap<String, String>(0);
	
	static {
		escapeChars.put("<", "&lt;");
		escapeChars.put(">", "&gt;");
		escapeChars.put("&", "&amp;");
		escapeChars.put("\"", "&quot;");
		escapeChars.put("'", "&apos;");
	}
	
	private StringUtil() {
	}

	public static boolean isEmpty(String str) {
		return isEmpty(str, true);
	}

	public static boolean isEmpty(String str, boolean isTrim) {
		if (isTrim) {
			return null == str || "".equals(str.trim());
		} else {
			return null == str || "".equals(str);
		}
	}

	public static boolean toBoolean(Object srcStr, boolean defaultValue) {
		try {
			if (srcStr != null) {
				return Boolean.parseBoolean(trim(srcStr.toString()));
			}
		} catch (Exception e) {
			;
		}
		return defaultValue;
	}

	public static boolean isInt(Object srcStr) {
		if (srcStr == null) {
			return false;
		}
		String s = srcStr.toString().replaceAll("(\\s)", "");
		Pattern p = Pattern.compile("([-]?[\\d]+)");
		Matcher m = p.matcher(s);
		return m.matches();
	}

	public static Integer toInteger(Object srcStr, Integer defaultValue) {
		try {
			if (srcStr != null && isInt(srcStr)) {
				String s = srcStr.toString().replaceAll("(\\s)", "");
				return s.length() > 0 ? Integer.valueOf(s) : defaultValue;
			}
		} catch (Exception e) {
			;
		}
		return defaultValue;
	}

	public static double toDouble(Object srcStr, double defaultValue) {
		try {
			if (srcStr != null) {
				return Double.parseDouble(trim(srcStr.toString()));
			}
		} catch (Exception e) {
			;
		}
		return defaultValue;
	}

	public static Double toDouble(Object srcStr, Double defaultValue) {
		try {
			if (srcStr != null) {
				return Double.valueOf(srcStr.toString().replaceAll(",", ""));
			}

		} catch (Exception e) {
			;
		}
		return defaultValue;
	}

	public static Long toLong(Object srcStr, Long defaultValue) {
		try {
			if (srcStr != null) {
				return Long.parseLong(trim(srcStr.toString()));
			}
		} catch (Exception e) {
			;
		}
		return defaultValue;
	}

	public static String trim(Object srcStr) {
		if (srcStr != null) {
			return srcStr.toString().trim();
		}
		return null;
	}

	/**
	 * tomcat对web.xml中url-pattern是否match的方法，请注意使用。
	 * 
	 * @param pattern
	 * @param requestPath
	 * @return
	 */
	public static boolean matchURLByTomcat(String pattern, String requestPath) {
		if (requestPath == null)
			return (false);
		// Match on context relative request path
		if (pattern == null)
			return (false);
		// Case 1 - Exact Match
		if (pattern.equals(requestPath))
			return (true);
		// Case 2 - Path Match ("/.../*")
		if (pattern.equals("/*"))
			return (true);
		if (pattern.endsWith("/*")) {
			if (pattern.regionMatches(0, requestPath, 0, pattern.length() - 2)) {
				if (requestPath.length() == (pattern.length() - 2)) {
					return (true);
				} else if ('/' == requestPath.charAt(pattern.length() - 2)) {
					return (true);
				}
			}
			return (false);
		}
		// Case 3 - Extension Match
		if (pattern.startsWith("*.")) {
			int slash = requestPath.lastIndexOf('/');
			int period = requestPath.lastIndexOf('.');
			if ((slash >= 0)
					&& (period > slash)
					&& (period != requestPath.length() - 1)
					&& ((requestPath.length() - period) == (pattern.length() - 1))) {
				return (pattern.regionMatches(2, requestPath, period + 1,
						pattern.length() - 2));
			}
		}
		// Case 4 - "Default" Match
		return (false); // NOTE - Not relevant for selecting filters
	}

	public static String unescape(String src) {
		if (isEmpty(src)) {
			return "";
		}
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					if(ch =='%'){
						tmp.append("\\" + ch);
					}else{
						tmp.append(ch);
					}
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					if(ch =='%'){
						tmp.append("\\" + ch);
					}else{
						tmp.append(ch);
					}
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	public static String escape(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charAt(i);
			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(unescape("%u597d"));
	}
	
	public static String htmlEscape(final String src) {
		if (isEmpty(src)) {
			return "";
		}
		String temp = src;
		for (String key : escapeChars.keySet()) {
			String value = escapeChars.get(key);
			temp = temp.replaceAll(key, value);
		}
		return temp;
	}
}
